package com.fishingwithme.infrastructure;

import com.fishingwithme.domain.CityService;
import com.fishingwithme.domain.circle.CircleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
@Component
public class CircleReportScheduledTasks {
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    // 并发控制锁，防止任务重叠执行
    private final AtomicBoolean cityRefreshLock = new AtomicBoolean(false);
    
    @Autowired
    private CircleService circleService;
    
    @Autowired
    private CityService cityService;

    // 每天凌晨2:00执行城市数据刷新任务
    @Scheduled(cron = "0 0 2 * * ?")
    public void refreshCityDataTask() {
        // 并发控制：如果上一次任务还未完成，跳过本次执行
        if (!cityRefreshLock.compareAndSet(false, true)) {
            log.warn("城市数据刷新任务跳过 - 上一次任务仍在执行中");
            return;
        }
        
        String time = LocalDateTime.now().format(formatter);
        log.info("开始执行城市数据刷新任务 - {}", time);
        
        try {
            cityService.refreshCityData();
            log.info("城市数据刷新任务执行成功 - {}", time);
        } catch (Exception e) {
            log.error("城市数据刷新任务执行失败 - {}", time, e);
            // 发送告警通知（可扩展）
        } finally {
            // 释放锁
            cityRefreshLock.set(false);
        }
    }

    // 1. Cron表达式：每天12:30执行
//    @Scheduled(cron = "0 30 12 * * ?")
//    public void dailyAfternoonTask() {
//        String time = LocalDateTime.now().format(formatter);
//        log.info("Cron中午任务执行 - {}", time);
//        circleService.scheduleCircleMessage();
//    }
//
//    // 2. Cron表达式：每天晚上10:30执行
//    @Scheduled(cron = "0 30 22 * * ?")
//    public void dailyEveningTask() {
//        String time = LocalDateTime.now().format(formatter);
//        log.info("Cron晚上任务执行 - {}", time);
//        circleService.scheduleCircleMessage();
//    }

//    @Scheduled(cron = "30 * * * * ?")
//    public void scheduleTestTask() {
//        String time = LocalDateTime.now().format(formatter);
//        log.info("Cron固定时间任务执行 - {}", time);
//        circleService.scheduleCircleMessage();
//    }
}
